<template>
	<div>

		<!-- 条件列表 -->
		<div style="text-align:left" v-if="flg.searchFlg">
			<el-form :inline="true" :model="queryCondition" class="demo-form-inline">
				<el-form-item label="用户名称" style="font-weight: bold">
					<el-input v-model="queryCondition.name" placeholder="用户名称" size="mini"></el-input>
				</el-form-item>
				<el-form-item label="手机号" style="font-weight: bold">
					<el-input v-model="queryCondition.tel" placeholder="手机号" size="mini"></el-input>
				</el-form-item>
				<el-form-item label="状态" style="font-weight: bold">
					<el-select v-model="queryCondition.isDelete" prop="isDelete" size="mini">
						<el-option label="正常" value="0"></el-option>
						<el-option label="停用" value="1"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="loadTeacherList" size="mini">查询</el-button>
				</el-form-item>
			</el-form>
		</div>
		<!-- 条件列表 -->

		<!-- 操作列表 -->
		<el-row style="margin-bottom:10px">
			<el-col :span="12" style="text-align:left">
				<el-button type="danger" icon="el-icon-minus" size="mini" plain @click="disableOrEnable('0')"
					v-show="!flg.batchDeleteFlg">批量停用</el-button>
				<el-button type="danger" icon="el-icon-minus" size="mini" plain @click="clickDelete()"
					v-show="flg.batchDeleteFlg">批量删除</el-button>

				<el-button type="warning" icon="el-icon-check" size="mini" plain @click="disableOrEnable('1')"
					v-show="flg.batchDeleteFlg">批量恢复</el-button>

				<el-button type="primary" icon="el-icon-plus" size="mini" plain
					@click="clickDialog('insert')">新增</el-button>
				<el-button type="warning" icon="el-icon-plus" size="mini" plain @click="clickDialog('update')"
					v-show="!flg.batchDeleteFlg">修改</el-button>

				<el-button type="success" icon="el-icon-plus" size="mini" plain @click="clickBoundRole()"
					v-show="!flg.batchDeleteFlg">关联角色</el-button>
			</el-col>
			<el-col :span="12" style="text-align:right">
				<el-tooltip class="item" effect="dark" :content="flg.searchFlg ? '隐藏搜索' : '展开搜索'" placement="top">
					<el-button icon="el-icon-search" size="mini" circle @click="flg.searchFlg = !flg.searchFlg"></el-button>
				</el-tooltip>
				<el-tooltip class="item" effect="dark" content="刷新" placement="top">
					<el-button icon="el-icon-refresh" size="mini" circle @click="loadTeacherList"></el-button>
				</el-tooltip>
			</el-col>
		</el-row>
		<!-- 操作列表 -->

		<!-- 用户列表 -->
		<el-table :data="teacherData" stripe style="width: 100%" v-loading="flg.loadingFlg"
			@selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column prop="id" label="序号" width="80">
				<template slot-scope="scope">
					<span>{{ (queryCondition.pageSize - 1) * queryCondition.pageNum + scope.$index + 1 }}</span>
				</template>
			</el-table-column>
			<el-table-column prop="name" label="姓名" width="150">
				<template slot-scope="scope">
					<el-tag size="medium" v-if="scope.row.isDelete == 0">{{ scope.row.name }}</el-tag>
					<el-tag size="danger" v-else>{{ scope.row.name }}</el-tag>
				</template>
			</el-table-column>
			<el-table-column prop="username" label="用户名" width="200">
			</el-table-column>
			<el-table-column prop="tel" label="手机号" width="150">
			</el-table-column>
			<el-table-column prop="isDelete" label="状态" width="80">
				<template slot-scope="scope">
					<el-tooltip :content="scope.row.isDelete == 0 ? '正常' : '停用'" placement="top">
						<el-switch :value="scope.row.isDelete == 0 ? true : false" active-color="#13ce66"
							inactive-color="#ff4949" @change="disableOrEnable(scope.row.isDelete, scope.row.id)">
						</el-switch>
					</el-tooltip>
				</template>
			</el-table-column>

			<el-table-column prop="roleName" label="关联角色" width="200">
				<template slot-scope="scope">
					<span v-for="(item, index) in scope.row.roleList" :key="index">
						{{ item.roleName }} <br />
					</span>
				</template>
			</el-table-column>

			<el-table-column prop="remark" label="备注" width="500">
				<template slot-scope="scope">
					<el-input type="textarea" v-model="scope.row.remark" :readonly="true"></el-input>
				</template>
			</el-table-column>
			
			<el-table-column prop="creator" label="创建人" width="150">
			</el-table-column>
			<el-table-column prop="createDate" label="创建时间" width="160">
				<template slot-scope="scope">
					{{ formatDate(scope.row.createDate) }}
				</template>
			</el-table-column>
			<el-table-column prop="modifier" label="修改人" width="150">
			</el-table-column>
			<el-table-column prop="modifyDate" label="修改时间" width="160">
				<template slot-scope="scope">
					{{ formatDate(scope.row.modifyDate) }}
				</template>
			</el-table-column>

			<el-table-column label="操作" fixed="right" width="100">
				<template slot-scope="scope">
					<button type="button" v-show="scope.row.isDelete == 1" class="el-button el-button--text el-button--mini"
						@click="clickDelete(scope.row.id)">
						<i class=" el-icon-edit">
							<span>彻底删除</span>
						</i>
					</button>

					<button type="button" v-show="scope.row.isDelete == 0" @click="clickDialog('update', scope.row.id)"
						class="el-button el-button--text el-button--mini">
						<i class="el-icon-edit">
							<span>修改</span>
						</i>
					</button>
					<button type="button" v-show="scope.row.isDelete == 0" @click="clickBoundRole(scope.row.id)"
						class="el-button el-button--text el-button--mini">
						<i class="el-icon-edit">
							<span>关联角色</span>
						</i>
					</button>

					<button type="button" v-show="scope.row.isDelete == 0 && scope.row.id != '10001'"
						class="el-button el-button--text el-button--mini" @click="clickResetPwd(scope.row.id)">
						<i class=" el-icon-edit">
							<span>重置密码</span>
						</i>
					</button>
				</template>
			</el-table-column>
		</el-table>
		<!-- 用户列表 -->

		<!--    分页框-->
		<div class="block">
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page="queryCondition.pageSize" :page-sizes="[5, 10, 20, 50, 100, 10000]"
				:page-size="queryCondition.pageNum" layout="total, sizes, prev, pager, next, jumper"
				:total="queryCondition.pageTotal">/
			</el-pagination>
		</div>
		<!--    分页框-->



		<!--    新增/修改 模态框-->
		<el-dialog :title="dialog.dialogTitle" :visible.sync="dialog.dialogFormVisible" width="40%" :append-to-body="true">
			<el-form :model="teacherForm" :rules="rules" ref="teacherForm" label-width="100px">

				<el-form-item label="姓名" prop="name">
					<el-input v-model="teacherForm.name" size="small"></el-input>
				</el-form-item>

				<el-form-item label="用户名称" prop="username">
					<el-input v-model="teacherForm.username" size="small"></el-input>
				</el-form-item>

				<el-form-item label="手机号" prop="tel">
					<el-input v-model="teacherForm.tel" size="small" maxlength="11"></el-input>
				</el-form-item>

				<el-form-item label="备注">
					<el-input type="textarea" v-model="teacherForm.remark" size="small"></el-input>
				</el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialog.dialogFormVisible = false">取 消</el-button>
				<el-button type="primary" @click="submitForm('teacherForm')">确 定</el-button>
			</div>
		</el-dialog>
		<!--    新增/修改 模态框-->

		<el-dialog title="关联角色" :visible.sync="dialog.dialogVisibleBoundFlg" width="30%" :append-to-body="true">
			<table border="0" width="100%" cellpadding="10">
				<tbody>
					<tr>
						<td width="50px">
							<span style="color: red;">*</span> 用户列表
						</td>
						<td>
							<el-select v-model="teacherAndRoleForm.teacherName" value-key="id" filterable clearable
								placeholder="请选择用户" size="small" style="width: 100%;" @change="queryBoundRole">
								<el-option v-for="item in teacherAndRoleForm.teacher" :key="item.id" :label="item.name"
									:value="item">
								</el-option>
							</el-select>
						</td>
					</tr>

					<tr>
						<td width="100px">
							&nbsp; 角色列表
							<el-tooltip class="item" effect="dark" content="关联角色" placement="top">
								<i class="el-icon-question"></i>
							</el-tooltip>
						</td>
						<td>
							<el-select v-model="teacherAndRoleForm.boundRole" value-key="id" multiple filterable clearable
								placeholder="请选择角色" size="small" style="width: 100%;">
								<el-option v-for="item in teacherAndRoleForm.role" :key="item.id" :label="item.roleName"
									:value="item">
								</el-option>
							</el-select>
						</td>
					</tr>

				</tbody>
			</table>

			<span slot="footer" class="dialog-footer">
				<el-button @click="dialog.dialogVisibleBoundFlg = false">取 消</el-button>
				<el-button type="primary" @click="submitFormBound()">确 定</el-button>
			</span>
		</el-dialog>
		<!-- 关联权限 -->
	</div>
</template>

<script>
import {
	requestTeacherData, requestAddTeacher, requestTeacherDataById,
	requestUpdateTeacher, requestBatchUpdateTeacherIsDelete,
	requestBatchDeleteTeacherById, requestResetPwd, requestTeacherAll,
	requestRoleAll, requestTeacherBoundRoles, requestQueryTeacherBoundRoles
} from "@/js/api/teacher"
import alter from '@/js/axios'
export default {
	name: "teacherIndex",
	data() {
		return {
			teacherData: [],
			multipleSelectionId: [],//多选的id
			flg: {
				loadingFlg: true,
				searchFlg: true,
				batchDeleteFlg: true,
			},
			//查询条件
			queryCondition: {
				pageSize: 1,//查询第几页
				pageNum: 10,//一页显示多少行
				isDelete: "0",
				name: "",
				tel: "",
				pageTotal: 0,//数据总数
			},
			//模态框的显示等
			dialog: {
				dialogFormVisible: false,
				dialogTitle: "",
				dialogVisibleBoundFlg: false
			},
			//需要新增、修改的表单内容
			teacherForm: {
				id: "",
				name: "",
				username: "",
				tel: "",
				remark: ""
			},
			//表单校验规则
			rules: {
				//姓名
				name: [
					{ required: true, message: "请输入姓名", trigger: 'blur' },
					{ min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
				],
				//用户名称
				username: [
					{ required: true, message: "请输入用户名称", trigger: 'blur' },
					{ min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
				],
				tel: [
					{ required: true, message: "请输入手机号", trigger: 'blur' },
					{ min: 2, max: 11, message: '长度在 2 到 11 个字符', trigger: 'blur' },
					{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
				]
			},
			//关联角色数据
			teacherAndRoleForm: {
				teacherName: "",//用户-选择的数据
				boundRole: [],//角色-选择的数据
				teacher: [],//所有用户数据
				role: []//所有角色数据
			},
		}
	},
	created() {
		//加载用户列表
		this.loadTeacherList()
	},
	methods: {
		handleSizeChange(val) {
			//  修改一页显示条数
			this.queryCondition.pageNum = val
			this.loadTeacherList()
		},
		handleCurrentChange(val) {
			//修改页数
			this.queryCondition.pageSize = val
			this.loadTeacherList()
		},
		handleSelectionChange(val) {
			//多选
			this.multipleSelectionId = []
			val.forEach(element => {
				this.multipleSelectionId.push(element.id)
			});
		},
		//查询用户绑定的角色
		queryBoundRole(value) {
			if (value == undefined || value == "") {
				this.teacherAndRoleForm.boundRole = []
				return
			}
			let data = {
				teacherId: value.id == undefined ? value : value.id
			}
			requestQueryTeacherBoundRoles(data).then(res => {
				this.teacherAndRoleForm.boundRole = res.data.data
			})
		},
		//点击关联角色
		clickBoundRole(id) {
			this.dialog.dialogVisibleBoundFlg = true
			//查询所有用户
			requestTeacherAll().then(res => {
				let data = res.data.data
				data.forEach((teacherData) => {
					if (teacherData.id == id) {
						this.teacherAndRoleForm.teacherName = teacherData
					}
				})
				this.teacherAndRoleForm.teacher = data
			})
			//查询所有角色
			requestRoleAll().then(res => {
				let data = res.data.data
				this.teacherAndRoleForm.role = data
			})
			if (id != undefined && id != "") {
				this.queryBoundRole(id)
			}
			return

		},
		//点击确认表单提交 权限关联
		submitFormBound() {
			console.log(this.teacherAndRoleForm,"0123as120")
			if (this.teacherAndRoleForm.teacherName == "") {
				alter.errorMessage("未选择用户")
				return false
			}
			let roleIds = []
			this.teacherAndRoleForm.boundRole.forEach(res => {
				roleIds.push(res.id)
			})
			let data = {
				teacherId: this.teacherAndRoleForm.teacherName.id,
				roleIds: roleIds.toString()
			}
			requestTeacherBoundRoles(data).then(() => {
				this.loadTeacherList()
				this.reset()
			})
			this.dialog.dialogVisibleBoundFlg = false
		},

		//点击显示新增/修改模态框
		clickDialog(type, id) {
			if (type == "insert") {
				this.dialog.dialogTitle = "新增角色"
				if (this.teacherForm.id != "") {
					this.reset()
				}
			} else if (type == "update") {
				this.dialog.dialogTitle = "修改角色"

				//如果id为空 代表是执行的选择操作
				if (id == undefined || id == "") {
					if (this.multipleSelectionId.length < 1) {
						alter.errorMessage("未选择数据！")
						return
					}
					if (this.multipleSelectionId.length > 1) {
						alter.errorMessage("只能选一条数据！")
						return
					}
					this.teacherForm.id = this.multipleSelectionId[0]
				} else {
					//否则就是单击操作
					this.teacherForm.id = id
				}

				this.selectTeacherById()
			}
			this.dialog.dialogFormVisible = true
		},
		//表单重置
		reset() {
			this.teacherForm = {
				id: "",
				name: "",
				username: "",
				tel: "",
				remark: ""
			}
			//关联角色数据
			this.teacherAndRoleForm.teacherName = {}//用户-选择的数据
			this.teacherAndRoleForm.boundRole = []//角色-选择的数据

			if (this.$refs['form'] !== undefined) {
				this.$refs['teacherForm'].resetFields();
			}
		},
		//停用/启用
		disableOrEnable(val, id) {
			//正常停用、恢复
			let title = val == 0 ? "停用后将不再显示！" : "是否确认启用。"
			this.$confirm(title + ', 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				let data = {
					ids: id,
					isDelete: val == 0 ? 1 : 0
				}
				if (id == undefined || id == "") {
					if (this.multipleSelectionId.length == 0) {
						alter.errorMessage("未选择数据！")
						return
					}
					//重新给ids赋值
					data.ids = this.multipleSelectionId.toString()
				}

				requestBatchUpdateTeacherIsDelete(data).then(() => {
					this.loadTeacherList()
				})
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消'
				});
			});
		},
		//点击确认表单提交（新增、删除）
		submitForm(formName) {
			this.$refs[formName].validate((valid) => {
				if (valid) {
					this.dialog.dialogFormVisible = false
					//true:添加菜单 false修改菜单
					if (this.teacherForm.id == "") {
						//调用新增用户
						this.insertTeacher()
					} else {
						//调用修改用户
						this.updateTeacher()
					}
				} else {
					return false;
				}
			})
		},
		//新增用户
		insertTeacher() {
			let data = {
				name: this.teacherForm.name,
				username: this.teacherForm.username,
				tel: this.teacherForm.tel,
				remark: this.teacherForm.remark
			}
			//调用新增用户的方法
			requestAddTeacher(data).then(() => {
				this.loadTeacherList()
				//新增成功 重置表单
				this.reset()
			})
		},
		//点击彻底删除权限按钮
		clickDelete(id) {
			this.$confirm("删除后将不可恢复，谨慎操作！！！", '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				let data = {
					ids: id
				}
				//如果id为空，代表执行的是批量操作
				if (id == undefined || id == "") {
					if (this.multipleSelectionId.length == 0) {
						alter.errorMessage("未选择数据！")
						return
					}
					//重新给ids赋值
					data = {
						ids: this.multipleSelectionId.toString(),
					}
				}

				requestBatchDeleteTeacherById(data).then(() => {
					this.loadTeacherList()
				})
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消删除'
				});
			});
		},
		//重置用户密码
		clickResetPwd(id) {
			this.$prompt('请输入重置后的密码', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				inputPattern: /^$|^.{6,}$/,
				inputErrorMessage: '重置密码不能小于6位'
			}).then(({ value }) => {
				let data = {
					id: id,
					password: value
				}
				requestResetPwd(data)
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '取消重置'
				});
			});
		},
		//修改用户
		updateTeacher() {
			let data = {
				id: this.teacherForm.id,
				name: this.teacherForm.name,
				username: this.teacherForm.username,
				tel: this.teacherForm.tel,
				remark: this.teacherForm.remark
			}
			//调用新增用户的方法
			requestUpdateTeacher(data).then(() => {
				this.loadTeacherList()
				//新增成功 重置表单
				this.reset()
			})
		},
		//通过id查询用户，渲染数据，实现修改
		selectTeacherById() {
			let data = {
				id: this.teacherForm.id
			}
			requestTeacherDataById(data).then(res => {
				let teacherByIdData = res.data.data
				this.teacherForm.id = teacherByIdData.id
				this.teacherForm.name = teacherByIdData.name
				this.teacherForm.username = teacherByIdData.username
				this.teacherForm.tel = teacherByIdData.tel
				this.teacherForm.remark = teacherByIdData.remark
			})
		},
		//加载用户列表
		loadTeacherList() {
			this.flg.loadingFlg = true
			//顶部按钮显示状态（批量停用、批量删除、批量恢复...）
			if (this.queryCondition.isDelete == 0) {
				this.flg.batchDeleteFlg = false
			} else {
				this.flg.batchDeleteFlg = true
			}

			let data = {
				pageSize: this.queryCondition.pageSize,
				pageNum: this.queryCondition.pageNum,
				delete: this.queryCondition.isDelete,
				name: this.queryCondition.name,
				tel: this.queryCondition.tel
			}

			//延迟加载，实现加载的视觉效果
			//调用加载用户数据的api
			requestTeacherData(data).then(res => {
				let teacherData = res.data.data
				this.teacherData = teacherData.list
				this.queryCondition.pageTotal = teacherData.size
			})
			this.flg.loadingFlg = false
		}
	}
}
</script>
<style scoped></style>